#!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
#
# copyright (c) 2009 renat nasyrov <renatn@gmail.com>.
#
# this file is part of konverta4.
#
# konverta4 is free software: you can redistribute it and/or modify
# it under the terms of the gnu general public license as published by
# the free software foundation, either version 3 of the license, or
# (at your option) any later version.
#
# konverta4 is distributed in the hope that it will be useful,
# but without any warranty; without even the implied warranty of
# merchantability or fitness for a particular purpose.  see the
# gnu general public license for more details.
#
# you should have received a copy of the gnu general public license
# along with konverta4.  if not, see <http://www.gnu.org/licenses/>.

import datetime
import re

from HTMLParser import HTMLParser

def get_color(date):
	""" Возвращает тип цвета дня недели, взависимости от текущей даты """

	t = datetime.date.today();
	if date < t:
		retval = 1
	elif date == t:
		retval = 2
	else:
		retval = 0
	return retval

class ExecutionParser(HTMLParser):
	def __init__(self, monday):
		self.in_b = False
		self.in_js = False
		self.detail = ""
		self.total = ""
		self.day = monday
		self.expenses = []
		self.script = ""
		self.pids = []
		self.weeklyBudget = ""
		HTMLParser.__init__(self)

	def handle_expenses(self, attrs):
		shred = lambda x: (x[0] == "name" and x[1].startswith("expenses[")) or x[0] == "value"
		a = filter(shred, attrs)
		if len(a) == 2:
			self.detail = a[1][1]

	def handle_total(self, attrs):
		shred = lambda x: (x[0] == "title") or (x[0] == "id"  and x[1].startswith("val-"))
		a = filter(shred, attrs)
		if len(a) == 2:
			self.in_b = True

	def handle_script(self):
		people = re.findall(r"personIds\[personIds.length\] = \'(?P<pid>\d+)\';", self.script)
		for p in people:
			self.pids.append(p)
		budget = re.findall(r"var weeklyBudget = (\d+\.\d*);", self.script)
		for e in budget:
			self.weeklyBudget = e
	
	def handle_starttag(self, tag, attrs):
		if tag == "input":
			self.handle_expenses(attrs)
		elif tag == "b":
			self.handle_total(attrs)
		elif tag == 'script':
			self.in_js = True

	def handle_data(self, data):
		if self.in_b:
			self.total += data
		elif self.in_js:
			self.script += data

	def handle_endtag(self, tag):
		if tag == "b" and self.in_b:
			color = get_color(self.day)
			data = (self.day, self.total, self.detail, color)
			self.expenses.append(data)
			self.total = ""
			self.day += datetime.timedelta(days=1)
			self.in_b = False
		elif tag == "script":
			self.in_js = False
			i = self.script.find("var noData")
			if i != -1:
				self.script = self.script[:i]
				self.handle_script()
			self.script = ""

	def get_execution(self):
		""" [<day of week>, <total of day>, <detail of day>, <color of day>, <left this day>] """
		execution = []
		total = 0
		total_weekly = float(self.weeklyBudget)
		days = 7
		for entry in self.expenses:
			total_day = 0
			if entry[1] != "-":
				total_day = float(entry[1])

			total_left = (total_weekly - total) / days - total_day
			total += total_day

			if entry[1] != "-":
				days -= 1
	
			new_entry = list(entry)
			new_entry.append(int(total_left))
			execution.append(tuple(new_entry))

		return execution

	def get_budget(self):
		return self.weeklyBudget

	def get_person(self):
		return self.pids[0]

